package com.jnu.keepaccounts.history;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jnu.keepaccounts.R;
import com.jnu.keepaccounts.data.Data;
import com.jnu.keepaccounts.data.DataBank;
import com.jnu.keepaccounts.data.DataTiaoMu;
import com.jnu.keepaccounts.data.DataTou;

import java.util.ArrayList;
import java.util.Calendar;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SelfFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SelfFragment extends Fragment {
    private ArrayList<Data> datas = new ArrayList<>();
    private RecyclerView recyclerView;
    private MyNewAdapter myAdapter;
    private DataBank dataBank ;
    final int[] month = new int[2];
    final int[] year = new int[2];
    final int[] day = new int[2];
    private TextView textView1;
    private LinearLayout linearLayout;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SelfFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SelfFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SelfFragment newInstance(String param1, String param2) {
        SelfFragment fragment = new SelfFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_self, container, false);
        Button button_next = view.findViewById(R.id.next);
        Button button_last = view.findViewById(R.id.last);

        //linearLayout = view.findViewById(R.id.linearLayout_tongji);
        dataBank = new DataBank(getContext());
        Calendar calendar = Calendar.getInstance();

        month[0] = month[1] = calendar.get(Calendar.MONTH) + 1;

        year[0] = year[1] =  calendar.get(Calendar.YEAR);

        day[0] = day[1] = calendar.get(Calendar.DAY_OF_MONTH);

        button_last.setText(year[0]+"-"+month[0]+"-"+day[0]);
        button_next.setText(year[1]+"-"+month[1]+"-"+day[1]);
        myAdapter = new MyNewAdapter(datas);
        textView1 = view.findViewById(R.id.empty_text);

        setData();



        button_last.setOnClickListener(v -> {
            //通过自定义控件AlertDialog实现
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            @SuppressLint("ResourceType") View view1 = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
            final DatePicker datePicker = (DatePicker) view1.findViewById(R.id.date_picker);
            //设置日期简略显示 否则详细显示 包括:星期\周
            datePicker.setCalendarViewShown(false);
            //设置date布局
            builder.setView(view1);
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //日期格式
                    year[0] = datePicker.getYear();
                    month[0] = datePicker.getMonth()+1;
                    day[0] = datePicker.getDayOfMonth();
                    button_last.setText(year[0] +"-"+ month[0] +"-"+ day[0]);
                    dialog.cancel();
                    setData();
                    myAdapter.notifyDataSetChanged();
                }
            });
            builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
        });

        button_next.setOnClickListener(v -> {
            //通过自定义控件AlertDialog实现
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            @SuppressLint("ResourceType") View view1 = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
            final DatePicker datePicker = (DatePicker) view1.findViewById(R.id.date_picker);
            //设置日期简略显示 否则详细显示 包括:星期\周
            datePicker.setCalendarViewShown(false);
            //设置date布局
            builder.setView(view1);
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //日期格式
                    year[1] = datePicker.getYear();
                    month[1] = datePicker.getMonth()+1;
                    day[1] = datePicker.getDayOfMonth();
                    button_next.setText(year[1] +"-"+ month[1] +"-"+ day[1]);
                    dialog.cancel();
                    setData();
                    myAdapter.notifyDataSetChanged();
                }
            });
            builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
        });


//        for(Data data:dataBank.loadData()){
//            if(data.getMonth()==month[0]&&data.getYear() == year[0]){
//                datas.add(data);
//            }
//        }

        recyclerView = view.findViewById(R.id.recyclerView_month);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(myAdapter);

        return view;
    }
    @SuppressLint("WrongConstant")
    public void setData(){
        dataBank = new DataBank(getContext());
        Calendar calendar = Calendar.getInstance();
        calendar.set(year[0],month[0],day[0]);
        Long last = calendar.getTimeInMillis();
        calendar.set(year[1],month[1],day[1]);
        Long next = calendar.getTimeInMillis();
        Long tem;
        datas.clear();
        for(Data data:dataBank.loadData()){
            calendar.set(data.getYear(),data.getMonth(),data.getDay());
            tem = calendar.getTimeInMillis();
            if(tem>=last&&tem<=next)
                datas.add(data);
        }
        if(datas.size() == 0 ){
           // linearLayout.setVisibility(8);
            textView1.setVisibility(0);
        }
        else {
            //linearLayout.setVisibility(0);
            textView1.setVisibility(8);
        }
        myAdapter.notifyDataSetChanged();
    }
    public class MyNewAdapter extends RecyclerView.Adapter<MyNewAdapter.ViewHolder>{
        ArrayList<Data> datas;

        MyNewAdapter(ArrayList<Data> datas){
            this.datas = datas;
        }
        public int getItemViewType(int position){
            return datas.get(position).getFlag();
        }
        @NonNull
        @Override
        public MyNewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if(viewType==2)return new MyNewAdapter.TouHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tou,parent,false));
            else return new MyNewAdapter.TiaoMuHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tiaomu,parent,false));
        }

        @SuppressLint("WrongConstant")
        @Override
        public void onBindViewHolder(@NonNull MyNewAdapter.ViewHolder holder, int position) {
            Data data = datas.get(position);
            if(data.getFlag()==2){

                DataTou dataTou = (DataTou)data;
                MyNewAdapter.TouHolder touHolder = (MyNewAdapter.TouHolder)holder;
                touHolder.date.setText(dataTou.getYear()+"-"+ dataTou.getMonth()+"-"+dataTou.getDay()+"");
                touHolder.shou.setText(dataTou.getShou()+"");
                touHolder.zhi.setText(Math.abs(dataTou.getZhi())+"");
            }
            else {
                DataTiaoMu dataTiaoMu = (DataTiaoMu) data;
                MyNewAdapter.TiaoMuHolder tiaoMuHolder = (MyNewAdapter.TiaoMuHolder) holder;
                tiaoMuHolder.image.setImageResource(dataTiaoMu.getImage());
                tiaoMuHolder.xiangmu.setText(dataTiaoMu.getXiangMu());
                tiaoMuHolder.laiyuan.setText(dataTiaoMu.getLaiYuan());
                tiaoMuHolder.shue.setText(dataTiaoMu.getShuE()+"");
                if(dataTiaoMu.getYusuan() == 1){
                    tiaoMuHolder.yusuan.setVisibility(0);
                }
            }
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }
        public class TouHolder extends MyNewAdapter.ViewHolder {
            TextView date;
            TextView shou;
            TextView zhi;

            public TouHolder(@NonNull View itemView) {
                super(itemView);
                date = (TextView) itemView.findViewById(R.id.textview_date);
                shou = (TextView) itemView.findViewById(R.id.textview_shou);
                zhi = (TextView) itemView.findViewById(R.id.textview_zhi);
            }
        }
        public class TiaoMuHolder extends MyNewAdapter.ViewHolder {
            ImageView image,yusuan;
            TextView xiangmu, laiyuan, shue;

            public TiaoMuHolder(@NonNull View itemView) {
                super(itemView);
                image = (ImageView) itemView.findViewById(R.id.imageview);
                xiangmu = (TextView) itemView.findViewById(R.id.textview_xiangmu);
                laiyuan = (TextView) itemView.findViewById(R.id.textview_laiyuan);
                shue = (TextView) itemView.findViewById(R.id.textview_shue);
                yusuan = (ImageView) itemView.findViewById(R.id.yusuan);
            }
        }
    }
}